package com.watson.nettydemo.demo06;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

/**
 * SimpleChannelInboundHandler 与 ChannelInboundHandlerAdapter 的区别，，SimpleChannelInboundHandler会将消息自动释放
 *
 * @author: llun
 * @date: 2022/3/11 14:54
 * @version: 1.0
 */
public class WebSocketServerHandler extends ChannelInboundHandlerAdapter {

    /**
     *  需求 将发过来的消息发回去
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        String text = ((TextWebSocketFrame) msg).text();
        ctx.channel().writeAndFlush(new TextWebSocketFrame("from client:"+text));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
